<template>
  <div class="home">
    <div class="platformleft">
      <div style="padding: 30px 20px">
        <div class="logobox" @click="goindex">
          <img
            style="width: 60px; height: 60px; margin-right: 5px"
            src="~@/assets/icon/gslogo.png"
          />
          <span>中字软科技</span>
        </div>
        <div>
          <el-button
            style="width: 100%; margin-bottom: 10px"
            type="primary"
            icon="el-icon-plus"
            @click="added()"
            >{{ $t("message.menu.newchat") }}</el-button
          >
          <span style="color: #9e9e9e">{{ $t("message.menu.show") }}</span>
        </div>
      </div>
      <!-- 可调节显示条数 -->
      <div class="lefttitle" style="height: 400px; overflow: hidden">
        <div v-for="(item, index) in sessiondata" :key="index">
          <el-button plain @click="getnewchat(item)">
            <div style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
              {{ item.chatSummary }}
            </div>
          </el-button>
        </div>
      </div>
    </div>
    <div class="chatright">
      <!-- <div v-html="message"></div> -->
      <div class="rollsize">
        <div class="headright">
          <el-dropdown style="margin-right: 30px" @command="setLanguage">
            <div class="el-dropdown-link">
              <img
                style="width: 25px"
                src="@/assets/img/icon_yy.svg"
                class="m_icon"
                alt=""
              />
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="zh">{{
                $t("message.menu.langsZh")
              }}</el-dropdown-item>
              <el-dropdown-item command="en">{{
                $t("message.menu.langsEn")
              }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown
            style="display: flex; justify-content: flex-end"
            @command="loginout"
          >
            <div style="text-align: right; padding-right: 15px">
              <img style="cursor: pointer" src="~@/assets/icon/icon_txbig.png" alt="" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="exit">{{$t('message.menu.logOut')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <!-- 对话区 -->
        <div class="roll">
          <div v-for="(item, index) in historydata" :key="index">
            <!-- 左边对话区 -->
            <div class="lefttalk" v-if="item.messageIdentifier == 'assistant'">
              <div class="talk">
                <div class="leftlogo">
                  <img style="cursor: pointer" src="~@/assets/icon/icon_zzr.png" alt="" />
                </div>
                <div class="inputL">
                  <div class="dialogbox" v-html="item.responseMessage"></div>
                </div>
              </div>
            </div>
            <!-- 右边对话区 -->
            <div
              class="righttalk"
              v-if="item.messageIdentifier == 'user' && item.responseMessage != ''"
            >
              <div class="talk" style="flex-direction: row-reverse">
                <div class="leftlogo">
                  <img
                    style="cursor: pointer"
                    src="~@/assets/icon/icon_txsmall.png"
                    alt=""
                  />
                </div>
                <div class="inputL">
                  <div
                    class="dialogbox"
                    style="border-radius: 10px 0 10px 10px"
                    v-html="item.responseMessage"
                  ></div>
                </div>
              </div>
            </div>
          </div>
          <!-- 等待左边 -->
          <div class="lefttalk" v-if="waitloading">
            <div class="talk">
              <div class="leftlogo">
                <img style="cursor: pointer" src="~@/assets/icon/icon_zzr.png" alt="" />
              </div>
              <div class="inputL">
                <div class="dialogbox">
                  <i class="el-icon-loading"></i>
                </div>
              </div>
            </div>
          </div>
          <!-- 底部 -->
          <div style="height: 15px; margin-bottom: 10px" id="footer"></div>
        </div>
      </div>

      <div class="chatinput">
        <div
          style="
            background: #fff;
            border-radius: 10px;
            box-shadow: 0px 0px 17px 2px rgba(0, 0, 0, 0.08);
          "
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 2 }"
            :placeholder="$t('message.menu.question')"
            v-model="requiredMessage"
            @keyup.enter.native="send()"
          ></el-input>
          <div style="text-align: right">
            <!-- <el-button style="margin: 10px" type="primary" size="small" @click="getchat()">发送</el-button> -->
            <el-button
              style="margin: 10px"
              type="primary"
              size="small"
              @click.native.prevent="send()"
              >{{$t('message.menu.pass')}}</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchEventSource } from "@microsoft/fetch-event-source";
import Cookies from "vue-cookies";
let token = Cookies.get("token");
export default {
  data() {
    return {
      // requiredMessage: "",
      leftrole: "1",
      questiondata: [],
      waitloading: false,
      interactionId: "",
      sessiondata: [],
      assistantdata: [],
      historydata: [],
      //
      source: null,
      userId: new Date().getTime(),
      requiredMessage: "",
      titleMessage: "",
      message: "",
      ctrl: null,
    };
  },
  computed: {},

  mounted() {},
  created() {
    let that = this;
    that.requiredMessage = that.$route.query.question;
    that.getsession();
    if (that.interactionId == "") {
      that.send();
    }
  },
  methods: {
    setLanguage(command) {
      if (this.$i18n.locale !== command) {
        this.$i18n.locale = command;
        localStorage.setItem("langs", command);
        location.reload();
      }
    },
    loginout(command) {
      if ((command = "exit")) {
        this.$router.push({ name: "login" });
      }
    },
    // 获取左侧会话记录
    getsession() {
      let that = this;
      that.$api.post("/chat/history/list", {}).then((res) => {
        that.sessiondata = res.records;
      });
    },
    // 滚动到最底部
    getfooter() {
      const element = document.getElementById("footer");
      element.scrollIntoView();
    },
    // 新建聊天
    added() {
      this.$router.push({ name: "added" });
    },
    goindex() {
      this.$router.push({ name: "index" });
    },
    //聊天记录
    getnewchat(item) {
      this.$router.push({ name: "newchat", query: { id: item.interactionId } });
    },

    send() {
      // 存储 Vue 实例的引用
      const self = this;
      self.waitloading = true;
      let requiredMessage = self.requiredMessage;
      let requestBody = {};
      requestBody.clientToken = new Date().getTime();
      if (self.interactionId != "") {
        requestBody.interactionId = self.interactionId;
      } else {
        requestBody.interactionId = null;
      }
      requestBody.question = encodeURI(requiredMessage);
      requestBody.openSearch = true;
      this.ctrl = new AbortController();
      // 放进数组用户所提问题
      var arrlist = {};
      if (self.interactionId != "") {
        var key1 = "interactionId";
        var value1 = self.interactionId;
        arrlist[key1] = value1;
      }
      var key2 = "responseMessage";
      var value2 = requiredMessage;
      var key3 = "messageIdentifier";
      var value3 = "user";
      arrlist[key2] = value2;
      arrlist[key3] = value3;
      self.historydata.push(arrlist); //push()在数组末端添加一条数据
      // 询问框清空
      self.requiredMessage = "";
      if (self.historydata.length > 2) {
        self.getfooter();
      }
      this.source = fetchEventSource("http://121.11.118.20:7001/treasure/conversation", {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/json",
          token: token,
        },
        body: JSON.stringify(requestBody),
        signal: this.ctrl.signal,

        onopen(event) {
          // 新增一条空数组
          var arrdata = {};
          if (self.interactionId != "") {
            var key1 = "interactionId";
            var value1 = self.interactionId;
            arrdata[key1] = value1;
          }
          var key2 = "responseMessage";
          var value2 = "";
          var key3 = "messageIdentifier";
          var value3 = "user";
          arrdata[key2] = value2;
          arrdata[key3] = value3;
          self.historydata.push(arrdata);

          self.titleMessage = "建立连接...\n";
          self.titleMessage += "---会话开始---\n";
          self.titleMessage += requiredMessage + "\n";
        },
        onmessage(event) {
          let dataReceive = event.data;
          if (self.historydata.length > 2) {
            self.getfooter();
          }
          let parseObject = JSON.parse(dataReceive);
          let data = parseObject.responseMessage;
          // 将角色属性塞进ai回答中
          var key3 = "messageIdentifier";
          var value3 = "assistant";
          parseObject[key3] = value3;
          // 替换未响应完是的最后一条数据作为ai回答
          if (parseObject.responseMessage != "SSE-END") {
            setTimeout(() => {
              self.waitloading = false;
              self.historydata.splice(self.historydata.length - 1, 1, parseObject);
            }, 300);
          }

          if (data.indexOf("SSE-END") !== -1) {
            self.closeSse();
            self.addMessageInnerHTML("\n");
            self.addMessageInnerHTML("\n");

            // 结束时刷新左侧会话列表
            self.getsession();
            return;
          }
          self.interactionId = parseObject.interactionId;
          self.setMessageInnerHTML(data);
        },
        onclose() {
          // 数据返回结束时触发
          self.closeSse();
        },
        onerror(event) {
          console.log("sse onerror:" + event);
          self.setMessageInnerHTML("连接关闭");
          self.closeSse();
        },
      });
    },

    closeSse() {
      this.ctrl.abort();
      const httpRequest = new XMLHttpRequest();
      httpRequest.open(
        "GET",
        "http://121.11.118.20:7001/treasure/test/sse/close/" + this.userId,
        true
      );
      httpRequest.send();
    },

    setMessageInnerHTML(innerHTML) {
      this.message = innerHTML;
    },

    addMessageInnerHTML(innerHTML) {
      this.message += innerHTML + "\n";
    },
  },
};
</script>
<style lang="stylus" scoped>
.home
  display flex
  min-height calc(100vh - 0px)

.platformleft{
  width:20%;
  background:#fff;
}
.chatright{
    width:80%;
    padding: 30px 50px;
    position: relative;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-image: url('~@/assets/icon/bg_index.png');
  }
  .logobox{
    cursor: pointer;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    span{
      width: 70%;
      font-size:18px;
      font-weight:600;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  >>>.el-textarea__inner{
    border: none;
  }
  .chatinput{
    padding: 0px 60px;
    position: fixed;
    bottom: 20px;
    width: 67%;
  }
  .talk{
    display: flex;
  }
  .dialogbox{
    background: #fff;
    padding: 10px 25px
    border-radius: 0 10px 10px 10px;
    margin: 10px;
    max-width: 500px;
    color: #284B67;
  }
  .lefttime{
      font-size:12px;
      color:#9EA2A4;
      margin:5px 10px
  }
  .lefttitle{
      >>>.el-button{
        border: 4px solid transparent;
        width: 100%;
        height:40px;
        border-radius: 0px;
      }
      >>>.el-button:hover{
        background:#F1F1F1;
        color:#606266;
      }
      >>>.el-button:focus{
        background:#F1F1F1;
        color:#606266;
        border-right:4px solid #0091FF
      }
    }
  .righttalk{
      padding-top:40px;
  }
  .roll{
      padding-bottom: 150px;
  }
  .rollsize{
      height: 35vw;
      overflow: overlay;
  }
  .rollsize::-webkit-scrollbar{
      width: 0.5rem; /* 设置滚动条的宽度 */
      background: transparent; /* 设置滚动条的背景色为透明 */
  }
  .rollsize::-webkit-scrollbar-thumb {
      background: transparent; /* 设置滚动条的拖动块的背景色为透明 */
  }
  .headright{
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
</style>
